package cn.player.act.vod;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haarman.listviewanimations.itemmanipulation.OnDismissCallback;
import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.player.R;
import cn.player.act.BaseActivity;
import cn.player.act.vod.VideoListActivity.DataAdapter.ViewHolder;
import cn.player.entity.VideoListItem;
import cn.player.utils.FragUtils;
import cntv.player.core.util.LogUtil;
import cntv.player.core.util.ToastUtil;
import cntv.player.engine.Const;
import cn.player.media.entity.VideoInfo;
import cn.player.media.fragment.MediaPlayFragment;
import cn.player.media.util.ParseUtil;

public class VideoListActivity extends BaseActivity {

    private String mUrlVideoList = "http://api.xiyou.cntv.cn/album/getalbumvideo?pid=100&albumid=27586&pagenum=1&pagesize=20&format=json";
    private String mUrlVideoListMore;
    private int pagenum = 1;
    private boolean isRefreshDone;
    private boolean isRefresh;
    private int total;

    private ListView mLvVideoList;
    private List<VideoListItem> videoListItems;
    private DataAdapter dataAdapter;
    private MediaPlayFragment mpFrag;
    private FrameLayout mFlPlayArea;
    private MediaPlayFragment.OnPlayerListener mOnPlayerListener;

    private int mCurrentPlay = -1;
    private ViewHolder mCurrentViewHolder;
    private int[] mPlayAreaLocation = new int[2];
    private int mStatusBarHeight;

    private int mCurrentPlayType = Const.PLAY_TYPE_PORT;
    private LinearLayout mLlLoading;
    private OnDismissCallback mOnDismissCallback;
    private SwingBottomInAnimationAdapter swingBottomInAnimationAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_list_activity);

        findViews();
        setListensers();
        initializeDate();
    }

    private void initializeDate() {
        // TODO Auto-generated method stub
        mUrlVideoListMore = mUrlVideoList;
        videoListItems = new ArrayList<VideoListItem>();
        initJsonData(mUrlVideoListMore);
    }

    private void setListensers() {
        // TODO Auto-generated method stub

        mLvVideoList.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub
                if (totalItemCount != 0 && (firstVisibleItem + visibleItemCount == totalItemCount)) {
                    if (!isRefreshDone && !isRefresh) {
                        if (videoListItems.size() < total) {
                            isRefresh = true;
                            refreshList();
                        } else {
                            loadMoreComplete();
                        }
                    }
                }

//				LogUtil.i("zl", "isPlayAreaInVisible = " + isPlayAreaInVisible());
                if (mpFrag == null) {
                    return;
                }
                if (isPlayAreaInVisibleOutTop()) {
                    setPlayAreaRightTop();
                } else if (isPlayAreaInVisibleOutBottom()) {
                    setPlayAreaRightBottom();
                } else if (isPortraitScreen()) {
                    mCurrentViewHolder = getViewHolder(mCurrentPlay);
                    if (mCurrentViewHolder != null) {
                        setPlayAreaPosition(mCurrentViewHolder.rl_play_area);
                    }
                }
            }
        });

        mOnPlayerListener = new MediaPlayFragment.OnPlayerListener() {

            @Override
            public void onPlayStart() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPlayPauseChanged(boolean isPaused) {
                // TODO Auto-generated method stub
                LogUtil.i("zl", "onPlayPauseChanged isPaused = " + isPaused);
            }

            @Override
            public void onPlayError(int errorNo, String errMsg) {
                // TODO Auto-generated method stub
                FragUtils.remove(FragUtils.getFragTran(VideoListActivity.this), mpFrag).commitAllowingStateLoss();
                mCurrentPlay = -1;
                mpFrag = null;
                ToastUtil.showToast(mContext, errMsg, ToastUtil.LENGTH_SHORT);
            }

            @Override
            public void onPlayComplete() {
                // TODO Auto-generated method stub
                FragUtils.remove(FragUtils.getFragTran(VideoListActivity.this), mpFrag).commitAllowingStateLoss();
                mCurrentPlay = -1;
                mpFrag = null;
                ToastUtil.showToast(mContext, "播放完成!", ToastUtil.LENGTH_SHORT);
            }
        };

        mOnDismissCallback = new OnDismissCallback() {

            @Override
            public void onDismiss(AbsListView listView, int[] reverseSortedPositions) {
                // TODO Auto-generated method stub

            }
        };

    }

    private void refreshList() {
        pagenum++;
        mUrlVideoListMore = mUrlVideoList.replace("pagenum=1", "pagenum=" + pagenum);
        initJsonData(mUrlVideoListMore);
    }

    /**
     * 加载更多完成
     */
    private void loadMoreComplete() {
        isRefresh = false;
        isRefreshDone = true;
//		mLvVideoList.onLoadComplete();
//		ToastUtil.showToast(mContext, R.string.msg_loaded_complete, Toast.LENGTH_SHORT);
    }

    private void findViews() {
        // TODO Auto-generated method stub
        mLvVideoList = (ListView) findViewById(R.id.lv_video_list);
        mFlPlayArea = (FrameLayout) findViewById(R.id.fl_video_play_area);
        setViewHeightPort(mFlPlayArea, false);

        mLlLoading = (LinearLayout) findViewById(R.id.ll_loading);
        mLvVideoList.setEmptyView(mLlLoading);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        if (isPortraitScreen()) {
            setPlayAreaPosition(mFlPlayArea, mPlayAreaLocation[0], mPlayAreaLocation[1] - mStatusBarHeight);
            setViewHeightPort(mFlPlayArea, false);
        } else {
            setPlayAreaPosition(mFlPlayArea, 0, 0);
            setViewHeightLand(mFlPlayArea);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!isPortraitScreen()) {
                setActivityOriention(PORT);
            } else {
                this.finish();
            }
            return true;
        }

        if (mpFrag != null) {
            mpFrag.onKeyDownVolume(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void initDataSuccess(String url, JSONObject response) {
        // TODO Auto-generated method stub
        super.initDataSuccess(url, response);
        try {
            total = response.optInt("total");
            List<VideoListItem> tempData = ParseUtil.parseDataToCollection(response, "data", VideoListItem.class);

            videoListItems.addAll(tempData);

            if (dataAdapter == null) {
                dataAdapter = new DataAdapter(videoListItems);
            } else {
                dataAdapter.setData(videoListItems);
            }


            if (swingBottomInAnimationAdapter == null) {
                swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(dataAdapter);
                swingBottomInAnimationAdapter.setAbsListView(mLvVideoList);
                mLvVideoList.setAdapter(swingBottomInAnimationAdapter);
            } else {
                swingBottomInAnimationAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            isRefresh = false;
        }
    }

    /**
     * 添加播放器
     */
    private void addPlayer(VideoInfo videoInfo) {
        if (mpFrag == null) {
            mpFrag = MediaPlayFragment.newInstance(videoInfo);
        } else if (mpFrag.isAdded()) {
            mpFrag.playVideo(videoInfo);
            return;
        }
        FragmentTransaction fragTran = getSupportFragmentManager().beginTransaction();
        if (!mpFrag.isAdded()) {
            fragTran.add(R.id.fl_video_play_area, mpFrag, "video_list_play");
        }
        fragTran.commit();
        mpFrag.setOnPlayerListener(mOnPlayerListener);
//		mpFrag.setOnShareListener(mOnShareListener);
    }

    /**
     * 计算当前数据在可见视图中的位置
     *
     * @param position
     * @return
     */
    public int getPositionFromVisible(int position) {
        return position + mLvVideoList.getHeaderViewsCount() - mLvVideoList.getFirstVisiblePosition();//加上头视图(下拉刷新占去的一个位置,或者头图)
    }

    /**
     * 获取当前数据所处视图
     *
     * @param position
     * @return
     */
    public View getView(int position) {
        return mLvVideoList.getChildAt(getPositionFromVisible(position));
    }

    /**
     * 获取当前数据所处视图容器
     *
     * @param position
     * @return
     */
    public ViewHolder getViewHolder(int position) {
        View childAt = getView(position);
        if (childAt != null) {
            return (ViewHolder) childAt.getTag();
        }
        return null;
    }


    /**
     * 判断当前播放的item是否从顶部滑出屏幕
     *
     * @return true 是， false 否
     */
    protected boolean isPlayAreaInVisibleOutTop() {
        int firstVisibleItem = mLvVideoList.getFirstVisiblePosition();
        int currentPlayPosition = mCurrentPlay + mLvVideoList.getHeaderViewsCount();

//		LogUtil.i("zl", "firstVisibleItem = " + firstVisibleItem + ",currentPlayPosition = " + currentPlayPosition);
        //说明当前item已从顶部滑出
        return firstVisibleItem > currentPlayPosition;
    }

    /**
     * 判断当前播放的item是否从底部滑出屏幕
     *
     * @return true 是， false 否
     */
    protected boolean isPlayAreaInVisibleOutBottom() {
        int lastVisiblePosition = mLvVideoList.getLastVisiblePosition();
        int currentPlayPosition = mCurrentPlay + mLvVideoList.getHeaderViewsCount();

//		LogUtil.i("zl", "lastVisiblePosition = " + lastVisiblePosition + ",currentPlayPosition = " + currentPlayPosition);
        //说明当前item已从底部滑出
        return lastVisiblePosition < currentPlayPosition;
    }


    /**
     * 设置播放区域跟随滑动，滑动时调用
     *
     * @param itemPlayArea
     */
    private void setPlayAreaPosition(View itemPlayArea) {
        itemPlayArea.getLocationOnScreen(mPlayAreaLocation);
//		LogUtil.i("zl", "location[0] = " + mPlayAreaLocation[0] + ",location[1] = " + mPlayAreaLocation[1]);
        if (mStatusBarHeight == 0) {
            mStatusBarHeight = getStatusBarHeight(this);
        }
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFlPlayArea.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.width = LayoutParams.MATCH_PARENT;
        layoutParams.height = screenWidth(mContext) * 9 / 16;
        layoutParams.leftMargin = mPlayAreaLocation[0];
        layoutParams.topMargin = mPlayAreaLocation[1] - mStatusBarHeight;
        layoutParams.rightMargin = 0;
        layoutParams.bottomMargin = screenHeight(mContext) - mPlayAreaLocation[1] - layoutParams.height;
        mFlPlayArea.setLayoutParams(layoutParams);

        if (mCurrentPlayType == Const.PLAY_TYPE_PORT) {
            return;
        }
        if (mpFrag != null) {
            mpFrag.updateMediaController(Const.PLAY_TYPE_PORT);
        }
        mCurrentPlayType = Const.PLAY_TYPE_PORT;
    }

    /**
     * 设置播放区域位置,用于横屏和竖屏切换时调用
     *
     * @param itemPlayArea
     * @param leftMargin
     * @param topMargin
     */
    private void setPlayAreaPosition(View itemPlayArea, int leftMargin, int topMargin) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFlPlayArea.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.width = LayoutParams.MATCH_PARENT;
        if (isPortraitScreen()) {
            layoutParams.height = screenWidth(mContext) * 9 / 16;
        } else {
            layoutParams.height = LayoutParams.MATCH_PARENT;
        }
        layoutParams.leftMargin = leftMargin;
        layoutParams.topMargin = topMargin;
        layoutParams.rightMargin = 0;
        layoutParams.bottomMargin = 0;
        mFlPlayArea.setLayoutParams(layoutParams);
    }

    /**
     * 设置播放区域位于右上角,当前正在播放的item滑出顶部时调用
     *
     */
    private void setPlayAreaRightTop() {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFlPlayArea.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.width = screenWidth(mContext) * 2 / 5;
        layoutParams.height = layoutParams.width * 9 / 16;
        int rightMargin = mContext.getResources().getDimensionPixelOffset(R.dimen.play_area_margin_right);
        layoutParams.leftMargin = screenWidth(mContext) - rightMargin - layoutParams.width;
        layoutParams.topMargin = rightMargin;
        layoutParams.rightMargin = rightMargin;
        layoutParams.bottomMargin = screenHeight(mContext) - rightMargin - layoutParams.height - mStatusBarHeight;
        mFlPlayArea.setLayoutParams(layoutParams);

        if (mCurrentPlayType == Const.PLAY_TYPE_RBC) {
            return;
        }
        if (mpFrag != null) {
            mpFrag.updateMediaController(Const.PLAY_TYPE_RBC);
        }
        mCurrentPlayType = Const.PLAY_TYPE_RBC;
    }

    /**
     * 设置播放区域位于右下角,当前正在播放的item滑出底部时调用
     *
     */
    private void setPlayAreaRightBottom() {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFlPlayArea.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.width = screenWidth(mContext) * 2 / 5;
        layoutParams.height = layoutParams.width * 9 / 16;
        int rightMargin = mContext.getResources().getDimensionPixelOffset(R.dimen.play_area_margin_right);
        layoutParams.leftMargin = screenWidth(mContext) - rightMargin - layoutParams.width;
        layoutParams.topMargin = screenHeight(mContext) - rightMargin - layoutParams.height - mStatusBarHeight;
        layoutParams.rightMargin = rightMargin;
        layoutParams.bottomMargin = rightMargin;
        mFlPlayArea.setLayoutParams(layoutParams);

        if (mCurrentPlayType == Const.PLAY_TYPE_RBC) {
            return;
        }
        if (mpFrag != null) {
            mpFrag.updateMediaController(Const.PLAY_TYPE_RBC);
        }
        mCurrentPlayType = Const.PLAY_TYPE_RBC;
    }

    public class DataAdapter extends BaseAdapter {

        private List<VideoListItem> mData;
        private ViewHolder viewHolder;

        public DataAdapter(List<VideoListItem> data) {
            super();
            this.mData = data;
        }

        public void setData(List<VideoListItem> data) {
            this.mData = data;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            // return data.size();
            return mData.size();
        }

        @Override
        public Object getItem(int index) {
            // TODO Auto-generated method stub
            return mData.get(index);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.player_list_item, null);

                viewHolder = new ViewHolder();
                viewHolder.rlRoot = (RelativeLayout) convertView.findViewById(R.id.rl_player_item_root);
                viewHolder.rl_play_area = (RelativeLayout) convertView.findViewById(R.id.rl_play_area);
                setViewHeightPort(viewHolder.rl_play_area, !isPortraitScreen());

                viewHolder.iv_photo = (ImageView) convertView.findViewById(R.id.iv_photo);
                viewHolder.iv_play_icon = (ImageView) convertView.findViewById(R.id.iv_play_icon);

                viewHolder.ll_video_handle = (LinearLayout) convertView.findViewById(R.id.ll_video_handle);
                viewHolder.tv_video_username = (TextView) convertView.findViewById(R.id.tv_video_username);
                viewHolder.iv_video_download = (ImageView) convertView.findViewById(R.id.iv_video_download);
                viewHolder.iv_video_fav = (ImageView) convertView.findViewById(R.id.iv_video_fav);
                viewHolder.iv_video_share = (ImageView) convertView.findViewById(R.id.iv_video_share);

                viewHolder.tv_video_title = (TextView) convertView.findViewById(R.id.tv_video_title);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            if (mData.get(position).getThumbpath() != null) {
                finalBitmap.display(viewHolder.iv_photo, mData.get(position).getThumbpath());
            }

            viewHolder.tv_video_title.setText(mData.get(position).getTitle());
            viewHolder.tv_video_username.setText(mData.get(position).getUsername());

            viewHolder.rl_play_area.setOnClickListener(new VideoListItemClickListener(position, viewHolder));
            viewHolder.iv_video_download.setOnClickListener(new VideoListItemClickListener(position, viewHolder));
            viewHolder.iv_video_fav.setOnClickListener(new VideoListItemClickListener(position, viewHolder));
            viewHolder.iv_video_share.setOnClickListener(new VideoListItemClickListener(position, viewHolder));

            return convertView;
        }


        class VideoListItemClickListener implements OnClickListener {

            private int position;
            private ViewHolder viewHolder;

            public VideoListItemClickListener(int position, ViewHolder viewHolder) {
                super();
                this.position = position;
                this.viewHolder = viewHolder;
            }

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {
                    case R.id.rl_play_area:
                        if (position == mCurrentPlay) {
                            return;
                        }
                        setPlayAreaPosition(viewHolder.rl_play_area);

                        VideoInfo videoInfo = new VideoInfo();
                        //点播基本信息
                        videoInfo.setPort(true);
                        videoInfo.setFlag(Const.VOD);
                        videoInfo.setRate(Const.PLAYER_MODE_SD);
                        videoInfo.setAspectRatio(Const.ASPECT_RATIO_LARGE);
                        videoInfo.setTitle(videoListItems.get(position).getTitle());
                        videoInfo.setVid(videoListItems.get(position).getPlayid());
                        addPlayer(videoInfo);

                        mCurrentPlay = position;

                        break;
                    case R.id.iv_video_download:
                        ToastUtil.showToast(mContext, "下载", ToastUtil.LENGTH_SHORT);
                        break;
                    case R.id.iv_video_fav:
                        ToastUtil.showToast(mContext, "收藏", ToastUtil.LENGTH_SHORT);
                        break;
                    case R.id.iv_video_share:
                        ToastUtil.showToast(mContext, "分享", ToastUtil.LENGTH_SHORT);
                        break;
                    default:
                        break;
                }
            }
        }

        public class ViewHolder {
            public RelativeLayout rlRoot;
            public RelativeLayout rl_play_area;
            public ImageView iv_photo;
            public ImageView iv_play_icon;

            public LinearLayout ll_video_handle;
            public TextView tv_video_username;
            public TextView tv_video_title;
            public ImageView iv_video_download;
            public ImageView iv_video_fav;
            public ImageView iv_video_share;

        }
    }


    /**
     * 设置竖屏的播放画面的高度，
     * 以及横屏播放完成时，恢复原始高度(横屏播放时高度充满屏幕了)
     *
     * @param iv
     * @param isFullScreen
     */
    public void setViewHeightPort(View iv, boolean isFullScreen) {
        LayoutParams layoutParams = iv.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = LayoutParams.MATCH_PARENT;
            if (isFullScreen) {//横屏
                layoutParams.height = screenHeight(mContext) * 9 / 16;
                LogUtil.i("zl", "横屏时 setViewHeightPort layoutParams.height = " + layoutParams.height);
            } else {//竖屏时，宽高正常
                layoutParams.height = screenWidth(mContext) * 9 / 16;
                LogUtil.i("zl", "竖屏时 setViewHeightPort layoutParams.height = " + layoutParams.height);
            }
            iv.setLayoutParams(layoutParams);
        }
    }

    /**
     * 设置view的高度
     *
     * @param iv
     */
    public void setViewHeightLand(View iv) {
        LayoutParams layoutParams = iv.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = screenWidth(mContext);
            layoutParams.height = screenHeight(mContext);
            iv.setLayoutParams(layoutParams);
        }
    }

    /**
     * 获取手机屏幕宽
     *
     * @param context
     * @return
     */
    public int screenWidth(Context context) {
        final int width = context.getResources().getDisplayMetrics().widthPixels;
        return width;
    }

    /**
     * 获取手机屏幕高
     *
     * @param context
     * @return
     */
    public int screenHeight(Context context) {
        final int height = context.getResources().getDisplayMetrics().heightPixels;
        return height;
    }


    /**
     * 是否竖屏
     *
     * @return
     */
    public boolean isPortraitScreen() {
        int mCurrentOrientation = mContext.getResources().getConfiguration().orientation;
        return mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT;
    }

    public void setActivityOriention(int oriention) {
        if (getRequestedOrientation() != oriention) {
            setRequestedOrientation(oriention);
        }
    }


    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public int getStatusBarHeight(Activity context) {
        Rect frame = new Rect();
        context.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        return statusBarHeight;
    }


}
